package com.zy.chat.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zy.chat.service.ChatService;
import com.zy.chat.service.MsgSessionService;
import com.zy.chat.session.SingleSession;
import com.zy.chat.util.ChatRedisUtils;
import com.zy.chat.util.TimeUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.ibatis.javassist.tools.web.Webserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SingleServiceImpl implements ChatService {


    @Autowired
    private MsgSessionService msgSessionService;

    private static final Logger log= LoggerFactory.getLogger(SingleServiceImpl.class);
    private static ChatRedisUtils chatRedisUtils;
    TimeUtils timeUtils = new TimeUtils();
    private static Map<String, List<String>> imageChunks = new HashMap<>();

    @Autowired
    public void init(ChatRedisUtils chatRedisUtils){
        SingleServiceImpl.chatRedisUtils=chatRedisUtils;
    }

    @Override
    public void SingleChat(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        JSONObject jsonObject  = JSONObject.parseObject(msg.text());
        String username=jsonObject.getString("username");
        String touser=jsonObject.getString("touser");
        String content=jsonObject.getString("content").replace("\n","");
        String type=jsonObject.getString("type");
        String chattype=jsonObject.getString("chattype");
        if ("pre-img".equals(type)) {
            // 接收到图片数据块
            storeImageChunk(username, touser, content);
        } else if ("img".equals(type)) {
            // 接收到最后一个图片数据块
            storeLastImageChunk(username, touser, content,type);
        }
        ChannelHandlerContext toUserCtx= SingleSession.getUserChannelMap().get(touser);
        if(!"img".equals(type)&&!"pre-img".equals(type)){
            Map map =chatRedisUtils.createChatNumber(touser,username,content,type);
            chatRedisUtils.hsaveCacheChatMessage(map);
        }
        if(toUserCtx==null){
            //调用离线的服务
            msgSessionService.offlineInsert(username,touser);
            sendMessage(ctx,"用户不在线");
        }else{
            JSONObject back = new JSONObject();
            back.put("fromUser", username);
            back.put("content", content);
            back.put("time",timeUtils.getCurrentTime());
            back.put("type",type);
            back.put("chattype",chattype);
            String jsonback=back.toJSONString();
            sendMessage(toUserCtx,jsonback);
        }
    }

    private void sendMessage(ChannelHandlerContext ctx, String responseJson) {
        log.info("服务器发回消息:"+responseJson);
        ctx.channel().writeAndFlush(new TextWebSocketFrame(responseJson));
    }

    private void storeImageChunk(String username, String touser, String content) {
        List<String> chunks = imageChunks.computeIfAbsent(touser, k -> new ArrayList<>());
        chunks.add(content);
    }

    // 存储最后一个图片数据块到缓冲区，并将完整的流存入 Redis
    private void storeLastImageChunk(String username, String touser, String content,String type) {
        List<String> chunks = imageChunks.get(touser);
        if (chunks != null) {
            chunks.add(content);

            // 将所有数据块合并为完整的流
            String fullImage = String.join("", chunks);

            // 存储完整的流到 Redis
           Map map=chatRedisUtils.createChatNumber(touser, username, fullImage, type);
            chatRedisUtils.hsaveCacheChatMessage(map);
            // 清除缓冲区中的数据块
            imageChunks.remove(touser);
        }
    }

}
